package Q2;


class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}


public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {

        ListNode curNode = pHead1;
        int len1 = 0;
        while (curNode != null) {
            len1++;
            curNode = curNode.next;
        }

        curNode = pHead2;
        int len2 = 0;
        while (curNode != null) {
            len2++;
            curNode = curNode.next;
        }

        ListNode p1 = pHead1;
        ListNode p2 = pHead2;


        //让 p1 与 p2 从同一位置开始运动
        while (len1 > len2) {
            p1 = p1.next;
            len1--;
        }

        while (len2 > len1) {
            p2 = p2.next;
            len2--;
        }

        while (p1 != null && p2 != null && p1 != p2) {
            p1 = p1.next;
            p2 = p2.next;
        }

        return p1;
    }
}
